import serial
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import time
PORT = "COM7"

#=建立与继电器的联系
def ConnectRely(PORT):
    try: 
        master = modbus_rtu.RtuMaster(serial.Serial(PORT, 9600, bytesize=8, parity='E', stopbits=1, xonxoff=0))
        master.set_timeout(5.0)
        master.set_verbose(True)
        """
        #master.execute(2, cst.READ_SINGLE_REGISTER, 0, 4)中
        #2为从机地址，cst.READ_SINGLE_REGISTER为读取单个寄存器，0为寄存器地址，4为读取寄存器个数
        """
        #读取保存寄存器
        holdR=master.execute(2, cst.READ_HOLDING_REGISTERS, 0, 4)
        print(holdR)
        #半双工通道，要留出时间间隔，防止读取输入寄存器失败
        # time.sleep(0.1)
        #读取输入寄存器
        inputR=master.execute(2, cst.READ_INPUT_REGISTERS, 0, 2)
        print(inputR)
        response_code =  1
        print("Connect Success")
        return response_code,master
    #错误描述和错误代码
    except modbus_tk.modbus.ModbusError as exc:
        print("%s- Code=%d" % (exc, exc.get_exception_code()))
#修改寄存器状态来开关风扇
def Switch(master,action):
    """
    master.execute(2, cst.WRITE_SINGLE_COIL, 0, output_value=1)中
    2为从机地址，cst.WRITE_SINGLE_COIL为写入单个线圈，0为线圈地址，output_value为输出值
    output_value为输出值，1为开，0为关
    """
    if action == "on":
        master.execute(2, cst.WRITE_SINGLE_COIL, 0, output_value=1)
    elif action == "off":
        master.execute(2, cst.WRITE_SINGLE_COIL, 0, output_value=0)


# master = ConnectRely(PORT)
response,master = ConnectRely(PORT)
time.sleep(0.1)

#语音识别模块联动
import speech
import time
speech.say("你好")
res = speech.input("Say something, please.")
speech.say("You said " + res)

def callback(phrase, listener):
    if phrase == "再见":
        listener.stoplistening()
    speech.say(phrase)
    if phrase == "开风扇":
        Switch(master,"on")
    elif phrase == "关风扇":
        Switch(master,"off")


listener = speech.listenforanything(callback)
while listener.islistening():
    time.sleep(.5)